package upload

import (
	"io"
	"mime/multipart"
	"os"
	"path/filepath"
	"server/global"
	"server/utils"
	"strings"
	"time"
)

type Local struct {
}

func (l *Local) UploadImage(file *multipart.FileHeader) (string, string, error) {
	ext := filepath.Ext(file.Filename)
	// 检查文件大小格式
	ok, err := CheckFile(ext, file)
	if !ok {
		return "", "", err
	}
	
	name := strings.TrimSuffix(file.Filename, ext)

	fileName := utils.MD5V([]byte(name)) + "-" + time.Now().Format("20060102150405") + ext
	path := global.Config.Upload.Path + "/image/"
	if err := os.MkdirAll(path, os.ModePerm); err != nil {
		return "", "", err
	}
	filePath := path + fileName

	// 写入文件
	outFile, err := os.Create(filePath)
	if err != nil {
		return "", "", err
	}
	defer func() { _ = outFile.Close() }()

	f, err := file.Open()
	if err != nil {
		return "", "", err
	}
	defer f.Close()

	if _, err = io.Copy(outFile, f); err != nil {
		return "", "", err
	}
	return "/" + filePath, fileName, nil
}

func (l *Local) DeleteImage(key string) error {
	path := global.Config.Upload.Path + "/image/" + key
	return os.Remove(path)
}
